package avicit.bdp.dcs.log.service;

import avicit.bdp.common.dto.ProcessInstanceDto;
import avicit.bdp.common.dto.TaskInstanceDto;
import avicit.bdp.common.service.dto.TaskSpeedDTO;
import avicit.bdp.common.utils.DateUtils;
import avicit.bdp.dcs.detail.dto.TaskTableLogDTO;
import avicit.bdp.dcs.detail.service.TaskTableLogService;
import avicit.bdp.dcs.job.service.DcsJobService;
import avicit.bdp.dcs.log.dto.TaskLogDetailDTO;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.DecimalFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * @金航数码科技有限责任公司
 * @作者：liyb
 * @邮箱：liyb@avic-digital.com
 * @创建时间： 2020-08-09 10:35
 * @类说明：日志服务类
 * @修改记录：
 */
@Service
public class LogService {

  private static final Logger logger = LoggerFactory.getLogger(LogService.class);

  public static final String TIME = "time";
  public static final String TASK_AVG_SPEED = "taskAvgSpeed";
  public static final String TASK_WRITE_SPEED = "taskWriteSpeed";
  public static final String FORMAT_STRING = "#.##";

  @Autowired private DcsTaskLogService taskLogService;
  @Autowired private DcsJobService jobService;
  @Autowired private TaskTableLogService tableLogService;

  /**
   * 获取任务性能数据
   * @param taskId
   * @param startTime
   * @param endTime
   * @return
   */
  public Map<String, List<Object>> getPerformanceByTaskId(
      String taskId, String startTime, String endTime) {
    Map<String, List<Object>> map = new HashMap<>(16);
    List<Object> timeList = new ArrayList<>();
    List<Object> taskAvgSpeedList = new ArrayList<>();
    List<Object> taskWriteSpeedList = new ArrayList<>();

    TaskSpeedDTO taskSpeedDTO = taskLogService.getTaskSpeedByTaskId(taskId);
    if (taskSpeedDTO == null) {
      map.put(TIME, timeList);
      map.put(TASK_AVG_SPEED, taskAvgSpeedList);
      map.put(TASK_WRITE_SPEED, taskWriteSpeedList);
      logger.info("没有查到数据，请确保taskId：{}对应的任务是否正常启动", taskId);
      return map;
    }

    // 数据量太多也只返回20条左右
    List<TaskLogDetailDTO> logDetailList;
    long num =
        taskLogService.selectCountByTaskInstanceId(
            taskSpeedDTO.getTaskInstanceId(), startTime, endTime);
    if (num > 20) {
      int interval = Math.round(num / 20) + 1;
      logDetailList =
          taskLogService.getIntervalPerformanceByTaskInstanceId(
              taskSpeedDTO.getTaskInstanceId(), startTime, endTime, interval);
    } else {
      logDetailList =
          taskLogService.getPerformanceByTaskInstanceId(
              taskSpeedDTO.getTaskInstanceId(), startTime, endTime);
    }

    DecimalFormat df = new DecimalFormat(FORMAT_STRING);
    if (CollectionUtils.isNotEmpty(logDetailList)) {
      for (TaskLogDetailDTO logDetail : logDetailList) {
        timeList.add(DateUtils.getDateByString(logDetail.getRecordTime()));
        // MB/s
        taskAvgSpeedList.add(df.format(logDetail.getTaskAvgSpeed()));
        taskWriteSpeedList.add(logDetail.getTaskWriteSpeed());
      }
    }

    map.put(TIME, timeList);
    map.put(TASK_AVG_SPEED, taskAvgSpeedList);
    map.put(TASK_WRITE_SPEED, taskWriteSpeedList);
    return map;
  }

  /**
   * 查询创建表日志
   *
   * @param processDefinitionId
   * @return
   */
  public String getTableLogByJobId(String processDefinitionId) {
    // 查询流程实例
    ProcessInstanceDto processInstanceDto =
        jobService.getProcessInstanceByProcessDefinitionId(processDefinitionId);
    if (processInstanceDto == null) {
      return "暂时未产生日志";
    }
    String processInstanceId = processInstanceDto.getId();

    String lastestTaskInstanceId = "";
    if (StringUtils.isNotEmpty(processDefinitionId)) {
      TaskInstanceDto taskInstanceDto =
          tableLogService.getLastestTaskInstanceByProcessDefinitionId(processDefinitionId);
      if (taskInstanceDto == null) {
        return "暂时未产生日志";
      }
      lastestTaskInstanceId = taskInstanceDto.getId();
    }

    TaskTableLogDTO tableLog =
        tableLogService.selectTableLog(processInstanceId, lastestTaskInstanceId);
    if (tableLog != null) {
      return tableLog.getTableLog();
    } else {
      return "暂时未产生日志";
    }
  }

  /**
   * 查询创建表日志
   *
   * @return
   */
  public String getTableLogByTaskId(String processInstanceId, String taskInstanceId) {
    TaskInstanceDto taskInstance = jobService.getTaskInstanceById(taskInstanceId);
    if (taskInstance == null) {
      return "暂时未产生日志";
    }
    String taskId = taskInstance.getName();

    TaskInstanceDto taskInstanceDto =
        tableLogService.getTaskInstanceByProcessInstanceId(processInstanceId, taskId);
    if (taskInstanceDto == null) {
      return "暂时未产生日志";
    }

    TaskTableLogDTO tableLog =
        tableLogService.selectTableLog(processInstanceId, taskInstanceDto.getId());
    if (tableLog != null) {
      return tableLog.getTableLog();
    } else {
      return "查询创建表日志失败";
    }
  }
}
